<template>
    <div class="collapsedFalse_logo" v-if="!mainStore().collapsed" :style="{ height: mainStore().avatarHeight + 'px' }">
        <a-upload name="file" list-type="picture" :headers="{ Authorization: authorization }" class="avatar-uploader"
            :show-upload-list="false" :action="uploadPhotoUrl" :before-upload="beforeUpload" @change="handleChange"
            accept="image/jpeg">
            <a-avatar shape="square" :size="100" :src="headerLogo" :loadError="loadErrorImage"
                style="cursor: pointer; border-radius: 7px" />
        </a-upload>
        <br />
        <a-dropdown>
            <a class="ant-dropdown-link">{{ user.displayName }}</a>
            <template #overlay>
                <a-menu>
                    <a-menu-item @click="personalInfoVisible = true">
                        {{ $t("main.personal") }}
                    </a-menu-item>
                    <a-menu-item @click="updatePwdVisible = true">
                        {{ $t("main.updatepwd") }}
                    </a-menu-item>
                </a-menu>
            </template>
        </a-dropdown>
    </div>
    <div class="collapsedTrue_logo" v-else :style="{ height: mainStore().avatarHeight + 'px' }">
        <a-dropdown>
            <a-avatar size="large" :src="headerLogo" />
            <template #overlay>
                <a-menu>
                    <a-menu-item @click="personalInfoVisible = true">
                        {{ $t("main.personal") }}
                    </a-menu-item>
                    <a-menu-item @click="updatePwdVisible = true">
                        {{ $t("main.updatepwd") }}
                    </a-menu-item>
                </a-menu>
            </template>
        </a-dropdown>
    </div>

    <a-modal :title="$t('main.personal')" centered :visible="personalInfoVisible" :maskClosable="false" @ok="personalInfoOk"
        @cancel="personalInfoCancel">
        <personal-info ref="personalInfoRef" v-if="personalInfoVisible" />
    </a-modal>

    <a-modal :title="$t('main.updatepwd')" centered :visible="updatePwdVisible" :confirm-loading="updatePwdLoading"
        :maskClosable="false" @ok="updatePwdOk" @cancel="updatePwdCancel">
        <update-pwd ref="updatePwdRef" v-if="updatePwdVisible" />
    </a-modal>
</template>

<script setup lang='ts'>
import i18n from '@/i18n';
import cache from '@/utils/cache';
import url from '@/utils/axios/url';
import defaultAvatar from '@/assets/images/defaultAvatar.jpg';
import { onMounted, reactive, ref, type Ref } from 'vue';
import { UserResultDto } from '@/models/user';
import { message, type UploadFile } from 'ant-design-vue';
import type { UploadChangeParam } from 'ant-design-vue/es/upload/interface';
import { mainStore } from '@/store/main';
import PersonalInfo from './avatar/personal-info.vue';
import UpdatePwd from './avatar/update-pwd.vue';

const uploadPhotoUrl: string = url.account + '/uploadphoto';
const authorization: string = 'Bearer ' + cache.getAccessToken();
const user: UserResultDto = reactive<UserResultDto>(cache.getUserInfo() ?? new UserResultDto);
const defaultImage: string = defaultAvatar;

const headerLogo: Ref<string> = ref<string>(defaultImage);

const personalInfoRef = ref();
const personalInfoVisible: Ref<boolean> = ref<boolean>(false);
const personalInfoLoading: Ref<boolean> = ref<boolean>(false);
const updatePwdRef = ref();
const updatePwdVisible: Ref<boolean> = ref<boolean>(false);
const updatePwdLoading: Ref<boolean> = ref<boolean>(false);

onMounted(() => {
    if (user.photo) {
        headerLogo.value = url.imgGroup + user.photo;
    }
})

function loadErrorImage(): boolean {
    headerLogo.value = defaultImage;
    return false;
}

//上传图片成功后的回调
function uploadSuccess(data: string): void {
    user.photo = data;
    cache.setUserInfo(user);
}

/**
 * 文件状态改变的回调
 * @param info 
 */
function handleChange(info: UploadChangeParam): void {
    if (info.file.status === 'uploading') {
        return;
    }
    if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (imageUrl: string) => {
            uploadSuccess(info.file.response.data);
            headerLogo.value = imageUrl;
        });
    }
}

/**
 * 上传图片校验
 * @param file 
 */
function beforeUpload(file: UploadFile): number | boolean {
    const isJpg: boolean = file.type === 'image/jpeg';
    if (!isJpg) {
        message.error(i18n.global.t('main.required.jpeg'));
    }
    const isLt2M: number | boolean = file.size ?? 0 / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error(i18n.global.t('main.required.imageSize'));
    }
    return isJpg && isLt2M;
}

function getBase64(img: any, callback: Function): void {
    const reader: FileReader = new FileReader;
    reader.addEventListener('load', (ev: ProgressEvent<FileReader>) => callback(ev.target?.result));
    reader.readAsDataURL(img);
}

async function personalInfoOk(): Promise<void> {
    personalInfoLoading.value = true;
    const isOk: boolean = await personalInfoRef.value.ok();
    if (isOk) {
        personalInfoCancel();
        user.displayName = cache.getUserInfo()?.displayName ?? user.displayName;
    }
    personalInfoLoading.value = false;
}

function personalInfoCancel(): void {
    personalInfoVisible.value = false;
}

async function updatePwdOk(): Promise<void> {
    updatePwdLoading.value = true;
    const isOk: boolean = await updatePwdRef.value.ok();
    if (isOk) {
        updatePwdCancel();
    }
    updatePwdLoading.value = false;
}

function updatePwdCancel() {
    updatePwdVisible.value = false;
}
</script>

<style lang="less" scoped>
.collapsedFalse_logo {
    text-align: center;
    padding-top: 30px;
}

.collapsedTrue_logo {
    padding-top: 15px;
    text-align: center;
    cursor: pointer;
    margin-bottom: 15px;
}
</style>
